package com.example.privacy;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.PointF;
import android.os.Bundle;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dlazaro66.qrcodereaderview.QRCodeReaderView;

import com.example.privacy.Utils.SharedPreferencesUtils;
import com.example.privacy.dialog.ItemDialog;

import java.util.UUID;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class QRScannActivity extends AppCompatActivity {
    private QRCodeReaderView qrCodeReaderView;
    private UUID uuidTemp;
    private UUID uuidTemp2;
    private ItemDialog itemDialog;
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_q_r_scann);

        qrCodeReaderView = (QRCodeReaderView)findViewById(R.id.qrdecoderview);
        String type = SharedPreferencesUtils.getInstance(QRScannActivity.this).getString("type","");
        qrCodeReaderView.setOnQRCodeReadListener(new QRCodeReaderView.OnQRCodeReadListener() {
            @Override
            public void onQRCodeRead(String text, PointF[] points) {
                System.out.println("调用");
                try{
                    UUID uuid1 = UUID.fromString(text);
                    System.out.print(text);
                    uuidTemp = uuid1;
                    if(uuidTemp2 == null){
                        Scanner(uuid1.toString());
                        uuidTemp2 = uuid1;
                    }else if(!uuidTemp2.equals(uuidTemp)){
                        Scanner(uuid1.toString());
                    }
                }catch (Exception e){
                    Toast.makeText(QRScannActivity.this,"请扫描货物二维码",Toast.LENGTH_SHORT).show();
                }
            }
        });
        qrCodeReaderView.setQRDecodingEnabled(true);
        qrCodeReaderView.setAutofocusInterval(2000L);
        qrCodeReaderView.setTorchEnabled(false);
        qrCodeReaderView.setBackCamera();
        checkPermissionAndCamera();

    }

    @Override
    protected void onResume() {
        super.onResume();
//        qrCodeReaderView.startCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        qrCodeReaderView.stopCamera();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
    }
    /**
     * 检查权限并拍照。
     * 调用相机前先检查权限。
     */
    private void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(),
                Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            qrCodeReaderView.startCamera();

            //有调起相机拍照。
            //后面可以有其他应用
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    PERMISSION_CAMERA_REQUEST_CODE);
        }
    }
    /**
     * 处理权限申请的回调。
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            System.out.print("到这里执行");
            System.out.print(PackageManager.PERMISSION_GRANTED);
            System.out.print(grantResults[0]);
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //允许权限，有调起相机拍照。
                System.out.print("初次调用成功");
                qrCodeReaderView.startCamera();
            } else {
                //拒绝权限，弹出提示框。
                Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void Scanner(final String requestUuid){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = getString(R.string.baseUrl)+"/GetMessage";
                url = url + String.format("?key=%s", requestUuid);
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(null,"");
                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization","Bearer "+SharedPreferencesUtils.getInstance(QRScannActivity.this).getString("token", ""))
                        .post(body)
                        .build();
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        final String result = response.body().string();
                        if(result.split("，")[0].equals("快递信息错误")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(QRScannActivity.this, "未授权扫描站点，当前应在站点为"+result.split("，")[3], Toast.LENGTH_LONG).show();
                                }
                            });
                        }else{
                            System.out.println(result);
                            final Good go = JSON.parseObject(result, Good.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    itemDialog = new ItemDialog(QRScannActivity.this);
                                    itemDialog.setLocal1and2(go.getNowLocal(), go.getNextLocal());
                                    itemDialog.setOnYesOnclickListener("", new ItemDialog.onYesOnclickListener() {
                                        @Override
                                        public void YesClick() {
                                            sendNext(uuidTemp.toString());
                                            itemDialog.dismiss();
                                            Toast.makeText(QRScannActivity.this, "发往下一站", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    itemDialog.setNoclickListener("", new ItemDialog.onNoOnclickListener() {
                                        @Override
                                        public void NoClick() {
                                            itemDialog.dismiss();
                                            Toast.makeText(QRScannActivity.this, "未发往下一站", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    itemDialog.show();
                                }
                            });
                        }

                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(QRScannActivity.this,"网络请求出错", Toast.LENGTH_LONG);
                            }
                        });
                    }
                    response.body().close();
                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }
    public void sendNext(final String requestUuid){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = getString(R.string.baseUrl)+"/SendNext";
                url = url + String.format("?key=%s", requestUuid);
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(null,"");
                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization","Bearer "+SharedPreferencesUtils.getInstance(QRScannActivity.this).getString("token", ""))
                        .post(body)
                        .build();
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();

                    if(response.code()==200){

                        final String result = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(QRScannActivity.this, result, Toast.LENGTH_LONG).show();
                            }
                        });
                        //完善成功，并跳转
                    }else{

                    }
                    response.body().close();
                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }

}